import axios from 'axios'

/**
 * 中间件 接收了一个 next() 的 dispatch 函数，并返回一个 dispatch 函数
 * @param store
 * @returns {function(*=): function(*=)}
 */
export default store => next => action => {
  const {dispatch, getState} = store
  if (typeof action === 'function') {
    action(dispatch, getState)
    return
  }
  const {
    promise,
    types,
    afterSuccess,
    ...reset
  } = action

  if (!action.promise) {
    return next(action)
  }
  // 一般ajax请求都会有3种状态
  const [REQUEST, SUCCESS, ERROR] = types

  next({
    ...reset,
    type: REQUEST
  })

  const onSuccess = resp => {
    next({
      ...reset,
      result: resp.data,
      type: SUCCESS
    })
    if (afterSuccess) {
      afterSuccess(dispatch, getState, resp)
    }
  }

  const onError = resp => {
    next({
      ...reset,
      result: resp,
      type: ERROR
    })
  }

  return promise(axios).then(onSuccess, onError).catch(error => {
    console.error('Axios MIDDLEWARE ERROR:', error);
    onError(error)
  })

}
